/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.institution.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.Tools;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import com.koron.institution.approval.InstitutionAddService;
import com.koron.institution.approval.InstitutionEditService;
import com.koron.institution.bean.*;
import com.koron.institution.mapper.InstitutionFileHistoryMapper;
import com.koron.institution.mapper.InstitutionFileMapper;
import com.koron.institution.service.api.InstitutionService;
import com.koron.institution.uitls.BaseEntityUtil;
import com.koron.institution.uitls.BusinessCode;
import com.koron.system.domain.DistrictCorpRelation;
import com.koron.system.mapper.DistrictMapper;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
@PropertySource("classpath:institution.properties")
public class InstitutionServiceImpl implements InstitutionService, InitializingBean, AfterApprovalService {

    private final static  Logger logger = LoggerFactory.getLogger(Logger.class);

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Value("${institution_add_confirm}")
    private String institutionAddConfirm;

    @Value("${institution_discard_confirm}")
    private String institutionDiscardConfirm;

    @Value("${institution_edit_confirm}")
    private String institutionEditConfirm;

    @Value("${institution_file_template_key}")
    private String institutionFileTemplateKey;

    @Value("${law_institution_file_template_key}")
    private String lawInstitutionFileTemplateKey;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    MessageBean<InstitutionFileCond> checkAndProduceCond(String fileName, String corpCode, Integer institutionType, String categoryId, Integer page, Integer pageSize) {
        MessageBean<InstitutionFileCond> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), InstitutionFileCond.class);
        InstitutionFileCond cond = new InstitutionFileCond();
        if (StringUtils.isNotBlank(fileName)) {
            cond.setFileName(fileName);
        }
        if (StringUtils.isNotBlank(categoryId)) {
            cond.setCategoryId(categoryId);
        }
        if (StringUtils.isNotBlank(corpCode)) {
            cond.setCorpCodeCond(corpCode);
        }
        if (page != null && page > 0 && pageSize != null && pageSize > 0) {
            cond.setPage(page);
            cond.setPageSize(pageSize);
            cond.setStart((page - 1) * pageSize);
        }
        if (institutionType != null) {
            cond.setInstitutionType(institutionType);
        } else {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_TYPE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_TYPE.getDescription());
            return msg;
        }
        if (institutionType == 2) {
            if (StringUtils.isBlank(corpCode)) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getDescription());
                return msg;
            }
        }
        msg.setData(cond);
        return msg;
    }

    @Override
    public MessageBean<?> getInstitutionList(String fileName, String corpCode, Integer institutionType, Integer state, String categoryId, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            MessageBean<InstitutionFileCond> condMessageBean = checkAndProduceCond(fileName, corpCode, institutionType, categoryId, page, pageSize);
            if (condMessageBean.getCode() != 0) {
                return condMessageBean;
            }
            InstitutionFileCond cond = condMessageBean.getData();
            cond.setState(state);
            InstitutionFileMapper mapper = factory.getMapper(InstitutionFileMapper.class);
            List<InstitutionFile> list = mapper.getInstitutionListByCond(cond);
            Integer total = mapper.getTotalByCond(cond);
            DataBean<InstitutionFile> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(cond.getPage());
            dataBean.setPageSize(cond.getPageSize());
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 1 : total > pageSize ? total % pageSize == 0 ? total / pageSize : total / pageSize + 1 : 1);
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }

    MessageBean<?> checkInstitutionFile(InstitutionFile institutionFile, MessageBean msg) {
        if (institutionFile == null) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(institutionFile.getCategoryId())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(institutionFile.getFileName())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_FILE_NAME.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_FILE_NAME.getDescription());
            return msg;
        }
        if (institutionFile.getInstitutionType() == null) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_TYPE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_TYPE.getDescription());
            return msg;
        }
        if (institutionFile.getInstitutionType() == 2 && StringUtils.isBlank(institutionFile.getCorpCode())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getDescription());
            return msg;
        }
//        if (institutionFile.getPublicationDate() == null) {
//            msg.setCode(BusinessCode.EMPTY_INSTITUTION_PUBLICATION_DATE.getCode());
//            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_PUBLICATION_DATE.getDescription());
//            return msg;
//        }
//        if (institutionFile.getExecutionDate() == null) {
//            msg.setCode(BusinessCode.EMPTY_INSTITUTION_EXECUTION_DATE.getCode());
//            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_EXECUTION_DATE.getDescription());
//            return msg;
//        }
//        if (institutionFile.getExecutionDate().before(institutionFile.getPublicationDate())) {
//            msg.setCode(BusinessCode.INSTITUTION_PUBLICATION_DATE_AFTER_EXECUTION_DATE.getCode());
//            msg.setDescription(BusinessCode.INSTITUTION_PUBLICATION_DATE_AFTER_EXECUTION_DATE.getDescription());
//            return msg;
//        }
        return msg;
    }

    @Override
    public MessageBean<?> saveOrCommit(String institutionStr, StaffBean user, MultipartFile[] file) {
        MessageBean<InstitutionFile> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), InstitutionFile.class);
        SessionFactory factory = new SessionFactory();
        try {
            InstitutionFile institution = JSONObject.parseObject(institutionStr, InstitutionFile.class);
            if (institution == null) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION.getDescription());
                return msg;
            }
            InstitutionFileMapper mapper = factory.getMapper(InstitutionFileMapper.class);
            InstitutionFileHistoryMapper historyMapper = factory.getMapper(InstitutionFileHistoryMapper.class);
            checkInstitutionFile(institution, msg);
            if (msg.getCode() != 0) {
                return msg;
            }
            //检测重复
            Integer check = mapper.check(institution);
            if (check > 0) {
                factory.close(false);
                msg.setCode(BusinessCode.INSTITUTION_EXIST.getCode());
                msg.setDescription(BusinessCode.INSTITUTION_EXIST.getDescription());
                return msg;
            }
            //保存附件；
            List<String> keepAddressList = new ArrayList<>();
            List<String> keepPreAddressList = new ArrayList<>();
            if (StringUtils.isNotBlank(institution.getKeepAddressStr())) {
                String[] keepAddressArray = institution.getKeepAddressStr().split("[,，]");
                keepAddressList.addAll(Arrays.asList(keepAddressArray));
            }
            if (StringUtils.isNotBlank(institution.getKeepPreAddressStr())) {
                String[] keepPreAddressArray = institution.getKeepPreAddressStr().split("[,，]");
                keepPreAddressList.addAll(Arrays.asList(keepPreAddressArray));
            }
            if (file != null && file.length > 0) {
                for (MultipartFile f : file) {
                    if (file != null) {
                        String url = clientWrapper.uploadFile(f);
                        String filPath = url + "#" + f.getOriginalFilename();
                        keepAddressList.add(filPath);
                        String pdfPath = docConverterUtils.converterUpdate(f);
                        if (pdfPath != null) {
                            keepPreAddressList.add(pdfPath);
                        } else {
                            keepPreAddressList.add(filPath);
                        }
                    }
                }
            }
            if (keepAddressList == null || keepAddressList.isEmpty()) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_ATTACHMENT.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_ATTACHMENT.getDescription());
                return msg;
            }
            institution.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
            institution.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
            institution.setCode(Tools.getCode32());
            if (StringUtils.isBlank(institution.getId())) {
                //新增
                BaseEntityUtil.setAddBaseProperties(institution, user);
                institution.setCode(Tools.getCode32());
                mapper.insert(institution);
            } else {
                //修改
                BaseEntityUtil.setUpdateBaseProperties(institution, user);
                mapper.updateByPrimaryKeySelective(institution);
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    InstitutionFileHistory translateInstitutionToHistory(InstitutionFile institutionFile) {
        InstitutionFileHistory history = new InstitutionFileHistory();
//        history.setCategoryId(institutionFile.getCategoryId());
//        history.setCode(institutionFile.getCode());
//        history.setFileName(institutionFile.getFileName());
//        history.setFileCode(institutionFile.getFileCode());
//        history.setPublicationDate(institutionFile.getPublicationDate());
//        history.setExecutionDate(institutionFile.getExecutionDate());
//        history.setApplicableProvisions(institutionFile.getApplicableProvisions());
//        history.setRemark(institutionFile.getRemark());
//        history.setVersion(institutionFile.getVersion());
//        history.setDescription(institutionFile.getDescription());
//        history.setAttachment(institutionFile.getAttachment());
//        history.setInstitutionType(institutionFile.getInstitutionType());
//        history.setCorpCode(institutionFile.getCorpCode());
//        history.setIndicationIndex(institutionFile.getIndicationIndex());
//        history.setFlowInstanceId(institutionFile.getFlowInstanceId());
//        history.setExternalLink(institutionFile.getExternalLink());
//        history.setPreviewAttachment(institutionFile.getPreviewAttachment());
        BeanUtils.copyProperties(institutionFile, history);
        return history;
    }

    @Override
    public MessageBean<?> discardInstitution(String institutionId, StaffBean user) {
        MessageBean<InstitutionFile> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), InstitutionFile.class);
        SessionFactory factory = new SessionFactory();
        try {
            InstitutionFileMapper mapper = factory.getMapper(InstitutionFileMapper.class);
            InstitutionFileHistoryMapper historyMapper = factory.getMapper(InstitutionFileHistoryMapper.class);
            //根据id获取制度记录
            InstitutionFile institutionFile = mapper.selectByPrimaryKey(institutionId);
            if (institutionFile == null) {
                factory.close();
                msg.setCode(BusinessCode.INSTITUTION_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.INSTITUTION_NOT_EXIST.getDescription());
                return msg;
            }
            Integer value = mapper.deleteByPrimaryKey(institutionId);
            if (value <= 0) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription(BusinessCode.FAILURE.getDescription());
                return msg;
            }
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    MessageBean<InstitutionFileHistoryCond> checkAndProduceHistoryCond(String fileName, String corpCode, Integer institutionType, String version, Integer page, Integer pageSize) {
        MessageBean<InstitutionFileHistoryCond> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), InstitutionFileHistoryCond.class);
        InstitutionFileHistoryCond cond = new InstitutionFileHistoryCond();
        if (StringUtils.isNotBlank(fileName)) {
            cond.setFileName(fileName);
        }
        if (StringUtils.isNotBlank(version)) {
            cond.setVersion(version);
        }

        if (page != null && page > 0 && pageSize != null && pageSize > 0) {
            cond.setPage(page);
            cond.setPageSize(pageSize);
            cond.setStart((page - 1) * pageSize);
        }

        if (institutionType != null) {
            cond.setInstitutionType(institutionType);
        } else {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_TYPE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_TYPE.getDescription());
            return msg;
        }
        if (StringUtils.isNotBlank(corpCode)) {
            cond.setCorpCode(corpCode);
        } else if (institutionType == 3) {
            cond.setCorpCode(null);
        } else {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getDescription());
            return msg;
        }
        msg.setData(cond);
        return msg;
    }

    ;

    @Override
    public MessageBean<?> getHistoryList(String fileName, String corpCode, Integer institutionType, String version, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            InstitutionFileHistoryMapper historyMapper = factory.getMapper(InstitutionFileHistoryMapper.class);
            MessageBean<InstitutionFileHistoryCond> messageBean = checkAndProduceHistoryCond(fileName, corpCode, institutionType, version, page, pageSize);
            if (messageBean != null && messageBean.getCode() != 0) {
                return messageBean;
            }
            InstitutionFileHistoryCond historyCond = messageBean.getData();
            historyCond.setHistoryFlag(1);
            List<InstitutionFileHistory> list = historyMapper.getHistoryList(historyCond);
            int total = historyMapper.getTotal(historyCond);
            DataBean<InstitutionFileHistory> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(historyCond.getPage());
            dataBean.setPageSize(historyCond.getPageSize());
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 0 : total / pageSize);
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> getHistoryListByCode(String code, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            Integer start = null;
            if (page != null && page > 0 && pageSize != null && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            InstitutionFileHistoryMapper historyMapper = factory.getMapper(InstitutionFileHistoryMapper.class);
            List<InstitutionFileHistory> list = historyMapper.getHistoryListByCode(code, pageSize, start);
            int total = historyMapper.countHistoryListByCode(code);
            DataBean<InstitutionFileHistory> dataBean = new DataBean<>();
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 0 : total / pageSize);
            dataBean.setPageSize(pageSize);
            dataBean.setPageNo(page);
            dataBean.setTotalNumber(total);
            dataBean.setList(list);
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> saveFile(MultipartFile[] files) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), String.class);
        try {
            List<String> keepAddressList = new ArrayList<>();
            if (files != null && files.length > 0) {
                String url = clientWrapper.uploadFile(files[0]);
                String filpath = url + "#" + files[0].getOriginalFilename();
                keepAddressList.add(filpath);

            }
            msg.setData((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> deleteFile(String filePaths) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), String.class);
        try {
            if (StringUtils.isNotEmpty(filePaths)) {
                String[] delAttArray = filePaths.split("[,，]");
                for (String att : delAttArray) {
                    clientWrapper.deleteFile(att.split("#")[0]);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    MessageBean<?> checkEditInstitutionFileHistory(InstitutionFileHistory history, MessageBean msg, InstitutionFileMapper mapper) {
        if (history == null) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(history.getCategoryId())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(history.getFileName())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_FILE_NAME.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_FILE_NAME.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(history.getVersion())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_VERSION.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_VERSION.getDescription());
            return msg;
        }
        if (history.getInstitutionType() == null) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_TYPE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_TYPE.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(history.getCorpCode())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getDescription());
            return msg;
        }
        if (history.getPublicationDate() == null) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_PUBLICATION_DATE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_PUBLICATION_DATE.getDescription());
            return msg;
        }
        if (history.getExecutionDate() == null) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_EXECUTION_DATE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_EXECUTION_DATE.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(history.getCode())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CODE.getDescription());
            return msg;
        }
        List<InstitutionFile> institutionFiles = mapper.queryInstitutionByCode(history.getCode());
        if (institutionFiles == null || institutionFiles.size() == 0) {
            msg.setCode(BusinessCode.INSTITUTION_NOT_EXIST.getCode());
            msg.setDescription(BusinessCode.INSTITUTION_NOT_EXIST.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(history.getAttachment())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_ATTACHMENT.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_ATTACHMENT.getDescription());
            return msg;
        }
        return msg;
    }

    MessageBean<?> checkEditInstitutionFile(InstitutionFile institutionFile, MessageBean msg, InstitutionFileMapper mapper) {
        if (institutionFile == null) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION.getDescription());
            return msg;
        }
        //判断是否有权限操作
        if (StringUtils.isBlank(institutionFile.getCategoryId())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CATEGORY_ID.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(institutionFile.getFileName())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_FILE_NAME.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_FILE_NAME.getDescription());
            return msg;
        }
        if (institutionFile.getInstitutionType() == null) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_TYPE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_TYPE.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(institutionFile.getCorpCode())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getDescription());
            return msg;
        }
        if (institutionFile.getPublicationDate() == null) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_PUBLICATION_DATE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_PUBLICATION_DATE.getDescription());
            return msg;
        }
        if (institutionFile.getExecutionDate() == null) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_EXECUTION_DATE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_EXECUTION_DATE.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(institutionFile.getCode())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_CODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CODE.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(institutionFile.getAttachment())) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_ATTACHMENT.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_ATTACHMENT.getDescription());
            return msg;
        }

        List<InstitutionFile> institutionFiles = mapper.queryInstitutionByCode(institutionFile.getCode());
        if (institutionFiles == null || institutionFiles.size() == 0) {
            msg.setCode(BusinessCode.INSTITUTION_NOT_EXIST.getCode());
            msg.setDescription(BusinessCode.INSTITUTION_NOT_EXIST.getDescription());
            return msg;
        } else {
            if (institutionFiles.stream().anyMatch(institution -> !institutionFile.getCorpCode().equals(institution.getCorpCode()))) {
                msg.setCode(401);
                msg.setDescription("没有操作权限");
                return msg;
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> getProcessData(String ids) {
        MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory();) {
            if (StringUtils.isNotBlank(ids)) {
                List<String> idList = JSONObject.parseArray(ids, String.class);
                if (idList != null && !idList.isEmpty()) {
//                    InstitutionFileMapper mapper = factory.getMapper(InstitutionFileMapper.class);
//                    List<InstitutionFile> list = mapper.queryListByIds(idList);
                    InstitutionFileHistoryMapper mapper = factory.getMapper(InstitutionFileHistoryMapper.class);
                    List<InstitutionFileHistory> list = mapper.queryListByIds(idList);
                    msg.setData(list);
                }
            } else {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_ID.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_ID.getDescription());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> getInstitutionByCode(String code) {
        MessageBean<Object> msg = MessageBean.create(0, "success", Object.class);
        try (SessionFactory factory = new SessionFactory();) {
            if (StringUtils.isNotBlank(code)) {
                InstitutionFileMapper mapper = factory.getMapper(InstitutionFileMapper.class);
                List<InstitutionFile> institutionFiles = mapper.queryInstitutionByCode(code);
                if (institutionFiles != null && !institutionFiles.isEmpty()) {
                    msg.setData(institutionFiles.get(0));
                }
            } else {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    InstitutionFile translateHistoryToInstitution(InstitutionFileHistory history) throws Exception {
        InstitutionFile institutionFile = new InstitutionFile();
        institutionFile.setCode(history.getCode());
        institutionFile.setCategoryId(history.getCategoryId());
        institutionFile.setFileName(history.getFileName());
        institutionFile.setFileCode(history.getFileCode());
        institutionFile.setPublicationDate(history.getPublicationDate());
        institutionFile.setExecutionDate(history.getExecutionDate());
        institutionFile.setApplicableProvisions(history.getApplicableProvisions());
        institutionFile.setRemark(history.getRemark());
        institutionFile.setVersion(history.getVersion());
        institutionFile.setDescription(history.getDescription());
        institutionFile.setAttachment(history.getAttachment());
        institutionFile.setState(2);
        institutionFile.setReviseState(0);
        institutionFile.setIndicationIndex(history.getIndicationIndex());
        institutionFile.setInstitutionType(history.getInstitutionType());
        institutionFile.setCorpCode(history.getCorpCode());
        institutionFile.setExternalLink(history.getExternalLink());
        institutionFile.setPreviewAttachment(history.getPreviewAttachment());
        return institutionFile;
    }

    @Override
    public MessageBean<?> batchEdit(String corpCode, List<InstitutionFile> institutionFileList, StaffBean user, String approverCodeListStr) {
        MessageBean<?> msg = MessageBean.create(0, "success", Object.class);
        if (StringUtils.isBlank(corpCode)) {
            corpCode = user.getCode();
        }
        if (StringUtils.isBlank(approverCodeListStr)) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
            return msg;
        }
        List<String> approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
        if (approverCodeList == null || approverCodeList.isEmpty()) {
            msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
            msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            InstitutionFileMapper mapper = factory.getMapper(InstitutionFileMapper.class);
            InstitutionFileHistoryMapper historyMapper = factory.getMapper(InstitutionFileHistoryMapper.class);
            for (InstitutionFile institutionFile : institutionFileList) {
                List<String> keepAddressList = new ArrayList<>();
                List<String> keepPreAddressList = new ArrayList<>();
                if (StringUtils.isNotBlank(institutionFile.getKeepAddressStr())) {
                    String[] keepAddressArray = institutionFile.getKeepAddressStr().split("[,，]");
                    keepAddressList.addAll(Arrays.asList(keepAddressArray));
                }
                if (StringUtils.isNotBlank(institutionFile.getKeepPreAddressStr())) {
                    String[] keepPreAddressArray = institutionFile.getKeepPreAddressStr().split("[,，]");
                    keepPreAddressList.addAll(Arrays.asList(keepPreAddressArray));
                }
                if (institutionFile.getFiles() != null && !institutionFile.getFiles().isEmpty()) {
                    for (MultipartFile file : institutionFile.getFiles()) {
                        if (file != null) {
                            String url = clientWrapper.uploadFile(file);
                            String filPath = url + "#" + file.getOriginalFilename();
                            keepAddressList.add(filPath);
                            String pdfPath = docConverterUtils.converterUpdate(file);
                            if (pdfPath != null) {
                                keepPreAddressList.add(pdfPath);
                            } else {
                                keepPreAddressList.add(filPath);
                            }
                        }
                    }
                }
                institutionFile.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
                institutionFile.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
                checkEditInstitutionFile(institutionFile, msg, mapper);
                if (institutionFile.getInstitutionType() == 5) {
                    DistrictMapper districtMapper = factory.getMapper(DistrictMapper.class);
                    DistrictCorpRelation districtCorpRelation = districtMapper.queryDistrictCorpByCorpCode(institutionFile.getCorpCode());
                    if (districtCorpRelation == null || StringUtils.isBlank(districtCorpRelation.getDitrictCode())) {
                        msg.setCode(BusinessCode.DISTRICT_NOT_EXIST.getCode());
                        msg.setDescription(BusinessCode.DISTRICT_NOT_EXIST.getDescription());
                        return msg;
                    }
                    institutionFile.setDistrictCode(districtCorpRelation.getDitrictCode());
                }
                if (msg != null && msg.getCode() != 0) {
                    factory.close(false);
                    return msg;
                }
            }
            List<String> idList = new ArrayList<>();
            List<String> historyIdList = new ArrayList<>();
            Date now = new Date();
            for (InstitutionFile ins : institutionFileList) {
//                BaseEntityUtil.setAddBaseProperties(history, user);
                InstitutionFile institutionFile = new InstitutionFile();
                institutionFile.setCorpCode(ins.getCorpCode());
                institutionFile.setFileName(ins.getFileName());
                institutionFile.setInstitutionType(ins.getInstitutionType());
                institutionFile.setCategoryId(ins.getCategoryId());
                institutionFile.setDistrictCode(ins.getDistrictCode());
                InstitutionFile institution = mapper.getInstitutionByFileName(institutionFile);
                if (institution != null && institution.getCode() != null && !institution.getCode().equals(ins.getCode())) {
                    msg.setCode(BusinessCode.INSTITUTION_EXIST.getCode());
                    msg.setDescription(BusinessCode.INSTITUTION_EXIST.getDescription());
                    factory.close(false);
                    return msg;
                }
                InstitutionFile orgInstitutionFile = mapper.selectByPrimaryKey(ins.getId());

                //生成审批记录
                ins.setAddTime(orgInstitutionFile.getAddTime());
                ins.setAddUser(orgInstitutionFile.getAddUser());
                ins.setAddTime(orgInstitutionFile.getAddTime());
                ins.setState(2);
                BaseEntityUtil.setUpdateBaseProperties(ins, user);
                InstitutionFileHistory auditRecord = translateInstitutionToHistory(ins);
                auditRecord.setId(DefaultIdGenerator.getInstance().generateLongId());
                auditRecord.setState(2);
                auditRecord.setHistoryFlag(0);
                auditRecord.setNewInstitutionId(orgInstitutionFile.getId());
                historyMapper.insert(auditRecord);
                //更新业务数据状态
                orgInstitutionFile.setState(2);
                mapper.updateByPrimaryKeySelective(orgInstitutionFile);
                historyIdList.add(auditRecord.getId());
                idList.add(ins.getId());
            }
            // 构造audit
            Audit audit = new Audit();
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(1);
            audit.setTarget(InstitutionEditService.class.getName());
            audit.setFlowName(institutionEditConfirm);
            //audit.setTitle( snap.getUpdateUser() + "提交了一份随手拍待确认");
            audit.setTitle(institutionEditConfirm);
            audit.setCorpCode(corpCode);
            audit.setInitiatorCode(user.getCode());
            audit.setDescription("法规制度修订");
            audit.setState(1);
            if (institutionFileList.get(0).getInstitutionType() == 1) {
                audit.setTemplateKey(lawInstitutionFileTemplateKey);
            } else {
                audit.setTemplateKey(institutionFileTemplateKey);
            }
            audit.setSetCode("institution_manage");
            audit.setInitiatorAccount(user.getUserid());
            audit.setBusinessIds(new Gson().toJson(historyIdList));
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : approverCodeList) {
                codes.append(code.split("_")[0]).append(",");
//                codes.append("1-").append(code.split("_")[0]).append(",");
            }
            businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("提交法规制度失败");
            } else {
//                try {
//                    mapper.updateFlowInstanceIdByIdList(idList, audit.getFlowInstanceId());
//                    historyMapper.updateFlowInstanceIdByIdList(historyIdList, audit.getFlowInstanceId());
//                } catch (Exception e) {
//                    logger.error("审批流程实例id保存失败!--------" + audit.getId());
//                }
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("提交法规制度成功");
                factory.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
        } finally {
            if (factory != null)
                factory.close();
        }
        return msg;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(InstitutionAddService.class.getName(), new InstitutionAddService());
        map.put(InstitutionEditService.class.getName(), new InstitutionEditService());
    }

    @Override
    public void editApproval(Audit audit) {

    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {

    }


    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
